package com.zn.controller;

import com.zn.pojo.RecordElement;
import com.zn.pojo.ServiceRecord;
import com.zn.pojo.UserRecord;
import com.zn.service.ServiceRecordService;
import com.zn.service.UserRecordService;
import com.zn.tools.MyTools;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author zhaoning
 * @Date 2024/7/16
 */

@ServerEndpoint("/chat")
@Component
@Slf4j
public class MainController {

    static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    static Integer justId = null;

    // 连接建立时执行
    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(), session);
        log.info("session_" + session.getId() + " is open.");
    }

    private static ServiceRecordService serviceRecordService;

    @Autowired
    public void setServiceRecordService(ServiceRecordService serviceRecordService) {
        MainController.serviceRecordService = serviceRecordService;
    }

    private static UserRecordService userRecordService;

    @Autowired
    public void setUserRecordService(UserRecordService userRecordService) {
        MainController.userRecordService = userRecordService;
    }

    // 收到一条消息
    @OnMessage
    public void onMessage(String text, Session session) throws IOException {
        log.info("收到一条消息: " + text);
        if (text.charAt(0) == '0') {
            text = text.substring(1);
            justId = Integer.parseInt(text);
            return;
        }
        text = text.substring(1);

        UserRecord userRecord = new UserRecord(null, justId, text, LocalDateTime.now());
        synchronized(userRecord) {
            userRecordService.save(userRecord);
        }

        String ans = PostMessageController.getAnswerBaidu(justId, getContent(justId), text);
        ServiceRecord newServiceRecord = new ServiceRecord();

        JSONObject jsonObject = new JSONObject(ans);
        newServiceRecord.setToId(justId);
        String msg = jsonObject.has("error_msg") ? "好的" : jsonObject.getString("result");
        newServiceRecord.setMessage(msg.length() > 80 ? msg.substring(0, 80) : msg);
        newServiceRecord.setCreateAt(LocalDateTime.now());

        ServiceRecord serviceRecord = serviceRecordService.save(newServiceRecord);
        if (serviceRecord != null) {
            log.info("已保存到数据库");
            System.out.println("已保存到数据库");
        }

//        sendMsg(newServiceRecord.getMessage());
        session.getBasicRemote().sendText(msg);
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        log.info("session_" + session.getId() + " is closed.");
    }


    public void sendMsg(String msg) throws IOException {
        for (Map.Entry<String, Session> session : sessionMap.entrySet()) {
            session.getValue().getBasicRemote().sendText(msg);
        }
    }

    private static String getContent(Integer id) {
        String res = "";
        // {\"role\":\"user\",\"content\":\"您好\"},
        // {\"role\":\"assistant\",\"content\":\"您好！有什么我可以帮助您的吗？请随时告诉我。\"},
        // {\"role\":\"user\",\"content\":\"帮我查查今年有多少天\"},
        // {\"role\":\"assistant\",\"content\":\"您好！根据常规的公历制度，今年的天数即2023年有365天。 希望以上信息对您有所帮助！\"}

        List<UserRecord> userRecordList = userRecordService.selectById(id);
        List<ServiceRecord> serviceRecordList = serviceRecordService.selectById(id);

        List<RecordElement> recordElementList = MyTools.getMessages(userRecordList, serviceRecordList);

        for (int i = 0; i < recordElementList.size() - 1; i++) {
            res += "{\"role\":\""
                    + (i % 2 == 0 ? "user" : "assistant") + "\","
                    + "\"content\":\""
                    + recordElementList.get(i).getMessage() + "\"},";
        }
        if (!recordElementList.isEmpty()) {
            res += "{\"role\":\"user\","
                    + "\"content\":\""
                    + recordElementList.get(recordElementList.size() - 1).getMessage() + "\"}";
        }
        System.out.println(res);
        return res;
    }
}













